package Heap;

import java.util.Arrays;

public class Heap {
    public int[] arr;
    public int usedSize;

    public Heap() {
        this.arr = new int[10];
    }

    public void initArr(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            this.arr[i] = arr[i];
            this.usedSize++;
        }
    }

    public void createHeap() {
        for (int parent = (this.usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, this.usedSize);
        }
    }

    private void siftDown(int parent, int usedSize) {
        int child = parent * 2 + 1;
        while (child < usedSize) {
            if (child + 1 < usedSize) {//有右孩子
                if (arr[child] < arr[child + 1]) {
                    child++;
                }
            }
            if (arr[parent] < arr[child]) {//创建大根堆
                swap(arr, parent, child);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    public void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public void offer(int val) {
        if (this.isFull()) {
            this.arr = Arrays.copyOf(this.arr, this.arr.length * 2);
        }
        this.arr[this.usedSize++] = val;

        this.siftUp(this.usedSize - 1);
    }

    public void siftUp(int child) {
        int parent = (child - 1) / 2;

        while (parent >= 0) {
            if (arr[parent] < arr[child]) {//创建大根堆
                swap(arr, parent, child);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public boolean isFull() {
        return this.usedSize == this.arr.length;
    }

    public int poll() {
        int val = arr[0];
        swap(arr, 0, this.usedSize - 1);
        this.usedSize--;
        this.siftDown(0, this.usedSize);

        return val;
    }

    public boolean isEmpty() {
        return this.usedSize == 0;
    }

    public int peek() {
        return this.arr[0];
    }

    //从小到大排序，创建大根堆
    public void sort() {
        int end = this.usedSize - 1;
        while (end >= 0) {
            swap(arr, 0, end);
            siftDown(0, end);
            end--;
        }
    }
}
